<?php
namespace MyAdmin\Controller;

use Think\Controller;

class SettlementsController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function index()
  {
    $page = I("page", 1);
    $page_size = I("page_size", 10);

    //查询
    $shop_name = trim(I("shop_name"));

    $beg_time = trim(I("beg_time"));
    $end_time = trim(I("end_time"));

    $where = "u.app_id={$this->app_id} ";
    if ($shop_name) {
      $where .= " and s.name like '%".trim($shop_name)."%'";
      $where_ar['shop_name']=$shop_name;
      $this->assign("shop_name", $shop_name);
    }

    if ($beg_time) {
      $where .= " and sm.day >= '$beg_time'";
      $where_ar['beg_time']=$beg_time;
      $this->assign("beg_time", $beg_time);
    }

    if ($end_time) {
      $where .= " and sm.day < '$end_time'";
      $where_ar['end_time']=$end_time;
      $this->assign("end_time", $end_time);
    }

    $field = "sm.*,s.name as shop_name";
    $order = "sm.id desc";
    $list = M('Settlements')->alias("sm")
      ->join("left join ".C("DB_PREFIX")."shops s on s.id=sm.shop_id")
      ->join("left join ".C("DB_PREFIX")."users u on u.shop_id=s.id")
      ->field($field)->where($where)->order($order)->page($page.",".$page_size)->select();

    $num = M('Settlements')->alias("sm")
      ->join("left join ".C("DB_PREFIX")."shops s on s.id=sm.shop_id")
      ->join("left join ".C("DB_PREFIX")."users u on u.shop_id=s.id")
      ->where($where)
      ->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num, $where_ar);
    $this->assign("page_list", $page_list);

    $this->display();
  }

  //设置打款
  public function change_status()
  {
    $model = M("settlements");
    $status = I("status", 2);
    $id = I("id", '');

    $post_data["status"] = $status;
    $post_data["updated_at"] = $this->now_time;
    $where = " id=".$id;
    $result = $model->where($where)->save($post_data);
    if ($result) {//$result!==false
      return_data("success", "change_status.users.success");
    } else {
      return_data("error", "change_status.users.error");
    }
  }

  public function do_statistics()
  {
    $settlement = M('settlements')->order('id desc')->find();

    if (!$settlement) {
      $end = strtotime('today');
      $end_today = date('Y-m-d 00:00:00', $end);
    } else {
      $start_day = $settlement['day'];
      $start = strtotime($settlement['day']);

      $end = strtotime('today');
      $end_today = date('Y-m-d 00:00:00', $end);
    }

    if ($start && $start_day) {
      $where = "o.payed_at >= {$start} AND o.payed_at < {$end} AND o.status in(2,4,5)";
    } else {
      $where = "o.payed_at < {$end} AND o.status in(2,4,5)";
    }

    $result = M('orders')->alias('o')
             ->where($where)
             ->join("left join ".C('DB_PREFIX')."shops s on s.id = o.shop_id")
             ->field('sum(o.total_amount) as total_amount, s.id as shop_id, o.id as order_id')
             ->group('o.shop_id')
             ->select();

    $rate = 6;
    foreach ($result as $item) {
      if (!$item['shop_id']) {
        continue;
      }

      $today_start = date('Y-m-d H:i:s', strtotime('today'));
      $today_end   = date('Y-m-d H:i:s', strtotime('today') + 86400);
      $row_where = "shop_id = {$item['shop_id']} AND created_at >= '{$today_start}' AND created_at < '{$today_end}'";

      $row = M('settlements')->where($row_where)->find();
      if ($row) {
        continue;
      }

      $rate_amount = floor($item['total_amount'] * (1000 - $rate) / 1000 * 100) / 100;

      $data = array(
        'shop_id' => $item['shop_id'],
        'total_amount' => $item['total_amount'],
        'rate_amount' => $rate_amount,
        'rate' => $rate,
        'status' => 1,
        'day' => $end_today,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
      );
      $settlement_id = M('settlements')->add($data);
      M('pay_logs')->where("order_id={$item['order_id']}")->save(array('settlement_id' => $settlement_id));
    }

    $this->success('操作成功', U('Settlements/index'));
  }

  /**
   * [定时更新订单完成]
   * @return [type] [description]
   */
  public function finish()
  {
    $today = strtotime('today');
    $payed_at = $today - 3600 * 24 * 10; //10天内

    $data = array(
      'updated_at' => $this->current_time,
      'status' => 5
    );
    M('orders')->where("payed_at <= {$payed_at} AND status in(2, 4)")
    ->save($data);

    $this->success('操作成功', U('Settlements/index'));
  }

  public function amount_logs()
  {
    $page = I("page", 1);
    $page_size = I("page_size", 10);
    $model = M("amount_logs");
    //查询
    $shop_name = trim(I("shop_name"));

    $beg_time = trim(I("beg_time"));
    $end_time = trim(I("end_time"));

    $flag = trim(I("flag"));
    $status = trim(I("status"));
    $types = trim(I("types", 1));
    $this->assign("types", $types);
    $where = "s.app_id={$this->app_id} and l.types=$types";
 
    if ($shop_name) {
      $where .= " and s.name like '%".trim($shop_name)."%'";
      $where_ar['shop_name']=$shop_name;
      $this->assign("shop_name", $shop_name);
    }
    if ($beg_time) {
      $beg_time_where = strtotime($beg_time);
      $where .= " and l.created_at>='".trim($beg_time_where)."'";
      $where_ar['beg_time']=$beg_time;
      $this->assign("beg_time", $beg_time);
    }
    if ($end_time) {
      $end_time_where = strtotime($end_time);
      $where .= " and l.created_at<'".trim($end_time_where)."'";
      $where_ar['end_time']=$end_time;
      $this->assign("end_time", $end_time);
    }
    if ($status) {
      $where .= " and l.status = '".trim($status)."'";
      $where_ar['status']=$status;
      $this->assign("status", $status);
    } else {
      $where .= " and l.status > 1 ";
    }
    $field = "l.*,s.name as shop_name";
    $order = "l.id desc";

    if($flag){
      $list = $model->alias("l")->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
      ->field($field)->where($where)->order($order)->select();
      flagAmount($list);
    }else{
      $list = $model->alias("l")->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
      ->field($field)->where($where)->order($order)->page($page.",".$page_size)->select();
    }
    foreach ($list as $key => &$value) {
      $value['created_at'] = local_time($value['created_at']);
      if ($value['payed_at']) $value['payed_at'] = local_time($value['payed_at']);

      switch ($value['status']) {
        case 1:
          $value['status_str'] = '余额记录';
          break;
        case 2:
          $value['status_str'] = "未打款";
          break;
        case 3:
          $value['status_str'] = "已打款";
          break;
        case 4:
          $value['status_str'] = "已拒绝";
          break;
        default:
          $value['status_str'] = "未知";
          break;
      }
      switch ($value['types']) {
        case 1:
          $value['types_str'] = '余额提现';
          break;
        case 2:
          $value['types_str'] = "返利提现";
          break;
        default:
          $value['types_str'] = "余额提现";
          break;
      }
    }

    $num = $model->alias("l")->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
                ->where($where)->count();

    $page_list = get_html_page_list($url_name, $list, $page, $page_size, $num, $where_ar);
    $this->assign("page_list", $page_list);

    $this->display();
  }

  public function wechat_pay()
  {
    $id = trim(I("id"));
    if (!$id) {
      $this->error('操作失败');
    }
    $log = M('amount_logs')->alias('l')
                           ->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
                           ->join("left join ".C("DB_PREFIX")."users u on u.shop_id=s.id")
                           ->where("l.id=$id and l.status=2")
                           ->field('l.*, u.xcx_openid,s.alipay_name truename')
                           ->find();
    if ($log) {
      $log['tran_no'] = "p".date("YmdHis", gmtime()).random(4, 1);
      $result = wxpay_to_shop($log);
      #更新记录
      if ($result['result_code'] && $result['result_code'] == 'SUCCESS') {

        $log_update = array(
          'status' => 3,
          'payed_at' => $this->now_time,
          'tran_no' => $log['tran_no'],
          'payment_no' => $result['payment_no']
        );
        M('amount_logs')->where("id=$id")->save($log_update);
        #更新提醒
        M('messages')->where("amount_log_id=$id and types in (2,6) and status<2")->save(array('status' => 2));

        send_payed_message_to_shop($id);

        $this->success('操作成功', U('Settlements/amount_logs', 'status=3'));
      } else {
        $this->error('操作失败:'.$result['err_code_des']);
      }
    } else {
      $this->error('操作失败:提现记录不存在或无效');
    }
  }

  public function reject()
  {
    $data = I('post.');
    $id = $data['id'];
    if (!$id) {
      $this->error('操作失败');
    }
    $log = M('amount_logs')->alias('l')
                           ->where("l.id=$id and l.status=2")
                           ->find();
    if ($log) {
      $log_update = array(
        'status' => 4,
        'reject_reason' => $data['reject_reason']
      );
      M('amount_logs')->where("id=$id")->save($log_update);
      if ($log['types'] == 1) {
        $amount = M('shops')->where("id={$log['shop_id']}")->getField('amount');
        $amount += $log['total_amount'];
        M('shops')->where("id={$log['shop_id']}")->save(array("amount" => $amount));
      } elseif ($log['types'] == 2) {
        $brokerage = M('shops')->where("id={$log['shop_id']}")->getField('brokerage');
        $brokerage += $log['total_amount'];
        M('shops')->where("id={$log['shop_id']}")->save(array("brokerage" => $brokerage));
      }

      #更新提醒
      M('messages')->where("amount_log_id=$id and types in (2,6) and status<2")->save(array('status' => 2));

      send_withdraw_reject_message_to_shop($id);

      $this->success('操作成功', U('Settlements/amount_logs', 'status=4'));
    } else {
      $this->error('操作失败:提现记录不存在或无效');
    }
  }

  public function withdraw()
  {
    $id = trim(I("id"));
    $where = array(
      'id' => $id,
      'status' => 2,
    );
    $log = M('amount_logs')->where($where)->find();
    if ($log) {
      #更新记录
      $log_update = array(
        'status' => 3,
        'payed_at' => $this->now_time
      );
      M('amount_logs')->where($where)->save($log_update);
      #更新提醒
      M('messages')->where("amount_log_id=$id and types=2 and status<2")->save(array('status' => 2));

      send_payed_message_to_shop($id);

      return_data('success','log.withdraw.success');
    } else {
      return_data('error','log.withdraw.invalid');
    }
  }

  public function show()
  {
    $id = I("id", 0);
    $log = M('amount_logs')->where("id=$id")->find();

    $log['created_at'] = local_time($log['created_at']);
    if ($log['payed_at']) $log['payed_at'] = local_time($log['payed_at']);
    switch ($log['pay_types']) {
      case 1:
        $log['pay_types_str'] = '微信提现';
        break;
      case 2:
        $log['pay_types_str'] = '支付宝提现';
        break;
      default:
        $log['pay_types_str'] = '未知';
        break;
    }

    $shop = M('shops')->where("id={$log['shop_id']}")
                      ->field('name, phone, alipay_account, alipay_name, wxpay_account')
                      ->find();

    $this->assign("log", $log);
    $this->assign("shop", $shop);

    $this->display();
  }
}
